﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;

namespace zuJianClient.PacketDto
{
    /// <summary>
    /// 设备登录系统[843]
    /// </summary>
    public class DeviceLogin
    {
        /// <summary>
        /// 厂家识别码 (32 字节) ascii
        /// </summary>
        public string ManufacturerId { get; set; }
        /// <summary>
        /// 设备的唯一标识码 (32字节) ascii
        /// </summary>
        public string DeviceId { get; set; }
        /// <summary>
        /// 校验和 (1 字节)
        /// </summary>
        public byte Checksum { get; set; } 

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="manufacturerCode"></param>
        /// <param name="uniqueIdentifier"></param>
        public DeviceLogin(string manufacturerId, string deviceId)
        {
            ManufacturerId = manufacturerId;
            DeviceId = deviceId;
        }

        /// <summary>
        /// 将对象转换为十六进制字符串
        /// </summary>
        /// <returns></returns>
        public string ToHexString()
        {
            // 将字符串转换为字节数组
            byte[] manufacturerBytes = Encoding.ASCII.GetBytes(ManufacturerId);
            byte[] deviceIdBytes = Encoding.ASCII.GetBytes(DeviceId);

            // 确保字节数组的长度符合预期
            manufacturerBytes = EnsureLength(manufacturerBytes, 32);
            deviceIdBytes = EnsureLength(deviceIdBytes, 32);

            // 计算校验和
            byte checksum = CalculateChecksum(ManufacturerId + DeviceId);

            // 将字节数组转换为十六进制字符串
            string manufacturerHex = BitConverter.ToString(manufacturerBytes).Replace("-", "");
            string deviceIdHex = BitConverter.ToString(deviceIdBytes).Replace("-", "");

            // 返回完整的十六进制字符串
            return manufacturerHex + deviceIdHex + checksum.ToString("X2");
        }
    }

    /// <summary>
    /// 登录回包
    /// </summary>
    public class DeviceLoginReturn {

        /// <summary>
        /// 用于设备显示的错误提示信息
        /// </summary>
        public string Content { get; set; }

        public DeviceLoginReturn(string hexString)
        {
            byte[] byteArray = StringToByteArray(hexString); // 将十六进制字符串转换为字节数组
            Content = Encoding.UTF8.GetString(byteArray); // 使用UTF-8编码将字节数组转换为字符串
        }
    }
}
